const ffi = require('koffi');
const path = require('path');
const { parentPort } = require('worker_threads');



let timer
//dll文件对照表
const dllPathMaps = ['sigang', 'tuoliduo_freshway', 'tuoliduo_freshstar']
function readWeight(currentScaleType) {
    
    
    let realPath = dllPathMaps[currentScaleType-1] || dllPathMaps[0]
    /*寺冈动态库*/

    // 根据环境变量调整dll路径
    let dllFilePath = `./${realPath}/pos_ad_dll.dll`;

    let dllPath = path.resolve(__dirname, dllFilePath)
    console.log('weightReaderWorker.js',dllPath)
    const lib = ffi.load(dllPath);//加载dll动态库
    const readWeightFunc = lib.func('int read_standard(char *rbuf)'); //读重
    let weightBuffer = Buffer.alloc(128, 0);//变量 weightBuffer 将引用一个新的 Buffer 对象，该对象有 128 个元素，每个元素都设置为 0
    //读称之前先清除一次定时器
    if (timer) {
        clearInterval(timer)
        timer = null
    }
    if (currentScaleType == '1') { ////当前称类型 默认为寺冈（1寺冈 2托利多_freshway 3托利多_freshstar）
        //console.log('sigang!!!')
        /*寺冈动态库end*/

        timer = setInterval(() => {
            if (readWeightFunc(weightBuffer) == 240) {
                // console.log(weightBuffer)
                let weight = weightBuffer.subarray(1, 8).toString('ascii').trim().replace(/[\x00-\x1F]/g, '');
                let tare = weightBuffer.subarray(9, 17).toString('ascii').trim().replace(/[\x00-\x1F]/g, '');
                // 发送消息给主线程
                parentPort.postMessage({ weight, tare });
            } else {
                parentPort.postMessage({ isError: true });
                //console.log('read-fail-2 read-weight-error!')
            }
        }, 350);
    } else if (currentScaleType == '2' || currentScaleType == '3') {
        //console.log('tuoliduo!!!')

        timer = setInterval(() => {
            // console.log('-------')
           
            if (readWeightFunc(weightBuffer) == 240) {
                // let weight = weightBuffer.subarray(1, 8).toString('ascii').trim().replace(/[\x00-\x1F]/g, '');
                // let tare = weightBuffer.subarray(9, 17).toString('ascii').trim().replace(/[\x00-\x1F]/g, '');
                // //这里使用parseFloat取小数点前的值，因为可能出现(00.xx 或 10.xx 或-00.),如果直接取值会导致多个0
                // weight =parseFloat(weight.split('.')[0])+'.'+weight.split('.')[1].substring(0,3) //小数点后取3位
                // tare =parseFloat(tare.split('.')[0])+'.'+tare.split('.')[1].substring(0,3) //小数点后取3位
                //  console.log({ weight,tare })
                // 发送消息给主线程

                //  console.log(weightBuffer.toString('ascii').trim().replace(/[\x00-\x1F]/g, ''))
                // const ret = weightBuffer.toString('utf8').replace(/\0/g, ''); // 去除空字符
                const ret = weightBuffer.toString('utf8')
                // console.log('ret',ret)
                let [weightValue, tareValue = '0.000'] = ret.substring(1).split('P'); // 分割净重和皮重
                //  console.log(weightValue,tareValue)

                //console.log(ret.substring(1).split('P'))
                weightValue = parseFloat(weightValue.split('.')[0]) + '.' + weightValue.split('.')[1].substring(0, 3) //小数点后取3位
                tareValue = parseFloat(tareValue.split('.')[0]) + '.' + tareValue.split('.')[1].substring(0, 3) //小数点后取3位

                // console.log('weightVal',weightValue)
                //console.log('tareVal',tareValue)

                parentPort.postMessage({ weight: weightValue, tare: tareValue });
            } else {
                parentPort.postMessage({ isError: true });
                //console.log('read-fail-2 read-weight-error!')
            }
        }, 350);

    }


}

// 停止读取重量
function stopReadingWeight() {
    if (timer) {
       // console.log('stopReadingWeight...........', timer)
        clearInterval(timer);
        timer = null;

    }
}



parentPort.on('message', ({ text, currentScaleType }) => { //主进程发送过来的消息

  console.log('currentScaleType',currentScaleType)
    if (text === 'startReadingWeight') {
      
        readWeight(currentScaleType);
    } else if (text === 'endReadingWeight') {
        stopReadingWeight();
    }
});